package com.conversationboard.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.controller.debug.ServletDebugInfo;
import com.conversationboard.database.Database;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.Bookmarks;
import com.conversationboard.model.User;
import com.conversationboard.security.EncryptedKey;
import com.conversationboard.security.EncryptionException;

@WebServlet(name = "DeleteSelectedBookmarksControllerServlet", urlPatterns = "/DeleteSelectedBookmarksControllerServlet")
public class DeleteSelectedBookmarksControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -6333402015938538591L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {
			User user = User.get(request.getUserPrincipal().getName());
			String[] tags = request.getParameterValues("checkbox");
			String key = request.getParameter("key");

			EncryptedKey encryptedKey = new EncryptedKey();

			if (!encryptedKey.isValid(key, user.getLoginId())) {
				Logger.log(new Date(), "Part 1 of error: " + this.getClass().getName(), user);
				String postRequest = ServletDebugInfo.getRawRequest(request);
				Logger.log(new Date(), "Part 2 of error:\n\n" + postRequest, user);
				return;
			}

			/* We're OK. Get the bookmarks, delete them and store them */

			Bookmarks bookmarks = user.getBookmarks();

			Connection connection = null;

			try {

				connection = Database.getConnection();
				connection.setAutoCommit(false);

				for (String tag : tags) {

					String[] parts = tag.split("-");
					int boardId = Integer.parseInt(parts[0]);
					int threadId = Integer.parseInt(parts[1]);

					Bookmarks.delete(connection, user.getUserId(), boardId, threadId);
				}

				connection.commit();

				/*
				 * Remove from the local copy once the database connection has
				 * successfully committed
				 */

				for (String tag : tags) {
					bookmarks.remove(tag);
				}

			} catch (SQLException e) {
				connection.rollback();
				throw e;
			} finally {
				Database.close(connection);
			}

			response.sendRedirect(Configuration.getInstance().getRoot() + "/index.jsp");

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (EncryptionException e) {
			throw new ServletException(e);
		}

	}

}
